#include "ultrasonicsensor.h"
#include "ultrasonicsensortest.h"
#include "ui_ultrasonicsensortest.h"
#include <unistd.h>

UltrasonicSensorTest::UltrasonicSensorTest(QWidget *parent):
 QDialog(parent),
  ui (new Ui::UltrasonicSensorTest)
{

    ui->setupUi(this);
    ultrasonicSensor = new UltrasonicSensor("/agvwork/AgvFundation/fundation/data/globalConfig/ultrasonicSensor/ultrasonicSensor.xml");

    ui->Serial_Port_Box->addItem(serialPortInfo.portName());
//    initialSerials_modbus();
}

UltrasonicSensorTest::~UltrasonicSensorTest()
{
    delete ui;
}

// 设置降噪电源槽函数
void UltrasonicSensorTest::on_Powter_Noise_Button_clicked()
{
    int noiseLevel = ui->Powter_Noise_Edit->text().toInt();
    int deviceId = ui->DeviceId_Edit->text().toInt(); 
    int stat = ultrasonicSensor->setPowerSupplyNoiseClass(deviceId, (EM_POWER_NOISE_CLASS)noiseLevel);
    if ( stat == 1)
    {
         ui->Output_View->setText("降噪电源设置成功。");
    }
    else
    {
         ui->Output_View->setText("降噪电源设置失败。");
    }
}

// 设置探测范围槽函数
void UltrasonicSensorTest::on_Detect_Range_Button_clicked()
{
    double detectRange = ui->Detect_Range_Edit->text().toDouble();
    int deviceId = ui->DeviceId_Edit->text().toInt();
    int stat = ultrasonicSensor->setDetectDistanceRange(deviceId, detectRange);
    if ( stat == 1)
    {
        ui->Output_View->setText("探测范围设置成功。");
    }
    else
    {
        ui->Output_View->setText("探测范围设置失败");
    }

}

// 设置RS485串口地址槽函数
void UltrasonicSensorTest::on_RS485_Address_Button_clicked()
{
    bool ok;
    int serialAddress = ui->RS485_Address_Edit->text().toInt(&ok,10);
    int origineAddress = ui->Origine_RS485_Address_Edit->text().toInt(&ok,10);
    int deviceId = ui->DeviceId_Edit->text().toInt(&ok,10);
    qDebug() << "on_RS485_Address: " << serialAddress;
    qDebug() << "serialAddress.toInt():" << serialAddress;
    qDebug() << "origineAddress.toInt():" << origineAddress;
    int stat;
    stat = ultrasonicSensor->setSensor485Address(deviceId,serialAddress);
    if ( stat == 1 )
    {
        ui->Output_View->setText("RS485串口地址设置成功。");
        qDebug() << "SerialPort stat" << stat;
    }
    else
    {
        ui->Output_View->setText("RS485串口地址设置失败");
    }
}


// 数据发送槽函数
void UltrasonicSensorTest::on_Data_Send_Button_clicked()
{
    QByteArray sendData;
    QSerialPort serialPort;
    serialPort.setPortName(ui->Serial_Port_Box->currentText());
    serialPort.open(QIODevice::ReadWrite);
    serialPort.setBaudRate( (QSerialPort::BaudRate) (ui->Baud_Box->currentText().toInt()) );
    serialPort.setDataBits( (QSerialPort::DataBits) (ui->Data_Bits_Box->currentText().toInt()) );
    serialPort.setParity(   (QSerialPort::Parity)   (ui->Parity_Box->currentText().toInt()) );
    serialPort.setStopBits( (QSerialPort::StopBits) (ui->Serial_Port_Box->currentText().toInt()) );
    serialPort.setFlowControl( (QSerialPort::FlowControl) (ui->Flow_Control_Box->currentText().toInt()) );

    serialPort.write( sendData.append(ui->Data_Input_Edit->text()));
    serialPort.close();

}


// 开始探测距离槽函数
void UltrasonicSensorTest::on_Begin_Detect_Button_clicked()
{
    int deviceId = ui->DeviceId_Edit->text().toInt();
    ui->Output_View->setText(QString::number(deviceId));
    double distant;
    int stat = ultrasonicSensor->getDetectDistanceFromBuffer(deviceId, distant);
    if ( stat == 1 )
    {
       ui->Output_View->setText("探测成功。");
       QString distanceData = QString("%1").arg(distant);
       qDebug() << "on_Begin_Detect_Button ==== distanceData:" << distanceData;
       ui->Distance_Edit->setText(distanceData);
    }
    else
    {
       ui->Output_View->setText("探测失败");
    }
}

void UltrasonicSensorTest::on_DeviceId_Button_clicked()
{
    ui->Output_View->clear();
}

void UltrasonicSensorTest::on_Data_Send_Button_test_clicked()
{

    int modbus_send_raw_request(modbus_t *ctx, uint8_t *raw_req, int raw_req_length);
    uint8_t raw_req[] = { 0xe8, 0x02, 0xb4};
    int req_length;
    uint8_t rsp[MODBUS_TCP_MAX_ADU_LENGTH];


    req_length = modbus_send_raw_request(modbusMaster, raw_req, 3 * sizeof(uint8_t));
    modbus_receive_confirmation(modbusMaster, rsp);
    short receiveData;
    receiveData=rsp[0]<<8;
    receiveData=receiveData+rsp[1];
    qDebug()<<"receiveData"<<receiveData;
    QString distanceData = QString::number(receiveData);
    ui->Distance_Edit->setText(distanceData);

}

void UltrasonicSensorTest::initialSerials_modbus()
{

    modbusMaster =modbus_new_rtu("/dev/ttyUSB0", 9600, 'N' , 8,   1);
//    modbus_set_slave(modbusMaster,0);
    if (modbus_connect(modbusMaster) == -1)
    {
           qDebug()<<"Modbus485Driver::connectPort connect failed";
        modbus_free(modbusMaster);
        modbusMaster=NULL;
        return ;
    }
    else
    {
//        modbus_set_response_timeout(modbusMaster, 0, 500000);
           qDebug()<<"connect success";
        return ;
    }
}

void UltrasonicSensorTest::on_button_setEnable_clicked()
{
    ultrasonicSensor->setSensorWork(ui->edit_location->text().toInt(),ui->checkBox->isChecked());
}
